package com.zzzy.doc.service.mydoc;

import com.zzzy.common.util.AssertUtil;
import com.zzzy.doc.common.enums.DocNotifyMessageModuleEnum;
import com.zzzy.doc.common.enums.DocStatusEnum;
import com.zzzy.doc.dao.entity.Document;
import com.zzzy.framework.common.enums.sys.UserStatusEnum;
import com.zzzy.framework.common.util.SecurityUtils;
import com.zzzy.sys.dto.UserInfoDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class MyDocAuditService extends MyDocService {

    @Transactional
    public void applyAudit(Long id, Long userId) {
        Document document = getDocByIdForUpdate(id);
        AssertUtil.isEquals(DocStatusEnum.AUDIT.getValue(), document.getStatus(), "公文状态错误，无法申请审核修订");
        Long loginUserId = SecurityUtils.getLoginUser().getId();
        AssertUtil.isNotEquals(userId, loginUserId, "选择的用户不能 为当前用户");
        AssertUtil.isTrue(userService.hasPermission(userId, "doc:process:audit"), "选择的用户无审核修订权限，如有疑问，请联系管理员");
        UserInfoDto userInfoDto = userService.getUserInfoById(userId);
        AssertUtil.isEquals(UserStatusEnum.ENABLE.getValue(), userInfoDto.getStatus(), "选择的用户状态错误，无法申请审核修订，如有疑问，请联系管理员");
        document.setUpdateTime(LocalDateTime.now());
        document.setOperatorId(userId);
        document.setOperatorName(userInfoDto.getNickName());
        baseMapper.updateById(document);

        docAdviceService.addAdvice(id, "向 " + userInfoDto.getNickName() + " 申请审核修订");
        String message = document.getSubject() + " 待审核修订";
        docNotifyMessageService.addNotifyMessage(id, userId, DocNotifyMessageModuleEnum.PROCESS_DOC, message);
    }

    @Transactional
    public void auditComplete(Long id) {
        Document document = getDocByIdForUpdate(id);
        docAdviceService.addAdvice(id, "审核修订完毕进入会签阶段");

        AssertUtil.isEquals(DocStatusEnum.AUDIT.getValue(), document.getStatus(), "公文状态错误，无法进入会签阶段");
        document.setStatus(DocStatusEnum.JOINT_SIGN.getValue());
        document.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(document);
    }

}
